<script setup>
import { Lock, Picture, User } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import {
  userGetValidateCodeService,
  userLoginService,
  userRegisterService
} from '@/api/user.js'
import { useUserStore } from '@/stores/index.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const isRegister = ref(false)

const formModel = ref({
  username: '',
  password: '',
  repassword: '',
  captcha: '', // 用户输入的验证码
  codeKey: '' // 后端返回的验证码key
})
const captchaSrc = ref('')
const refreshCaptcha = async () => {
  const res = await userGetValidateCodeService()
  console.log(res)
  formModel.value.codeKey = res.data.codeKey
  captchaSrc.value = res.data.codeValue
}

onMounted(() => {
  refreshCaptcha()
  console.log('captchaSrc ===' + captchaSrc.value)
})

const form = ref()

// useUserStore实际是个方法
const userStore = useUserStore()
const register = async () => {
  await form.value.validate()
  await userRegisterService(formModel.value)
  ElMessage.success('注册成功')
  isRegister.value = false
}

const router = useRouter()
const login = async () => {
  await form.value.validate()
  const res = await userLoginService(formModel.value)

  // 使用store前需要声明
  userStore.setToken(res.data.token)
  // ElMessage.success('登录成功')
  router.push('/')
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15的非空字符',
      trigger: 'blur'
    },
    {
      // 自定义校验
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'submit' }]
}
</script>

<template>
  <!--
  1. 布局相关
  el-form 整个表单组件
  el-form-item 表单的一行，一个表单域
  el-input 表单元素（输入框）

  2. 校验相关：
  el-form  => :model="formModel" v-model绑定整个表单数据
  el-from => :rules="rules" 绑定的整个rules规则对象
  表单元素 =>  v-model=formModel.xxx 给表单元素，绑定form的子属性
  el-form-item => prop配置生效的是哪个校验规则(和rules中的字段要对应）


-->
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
        :model="formModel"
        label-position="top"
        :rules="rules"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="formModel.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formModel.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
            v-model="formModel.repassword"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <el-form
        :model="formModel"
        ref="form"
        size="large"
        autocomplete="off"
        :rules="rules"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            :prefix-icon="Picture"
            type="text"
            placeholder="请输入验证码"
            v-model="formModel.captcha"
          >
            <template v-slot:append>
              <img
                class="captcha-image"
                :src="captchaSrc"
                @click="refreshCaptcha"
                alt="验证码"
              />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="login"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background: url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
    .captcha {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    .captcha-image {
      cursor: pointer;
      margin-left: 10px;
      height: auto;
    }
  }
}
</style>
